#include "padgraphicsview.h"
#include "circleitem.h"
#include <cmath>
#include <QGraphicsPixmapItem>
#include <opencv2/opencv.hpp>
#include "CaliCam.hpp"

PadGraphicsView::PadGraphicsView(QWidget *parent):
    QGraphicsView(parent)
{
    m_scene = new QGraphicsScene;
    QPixmap backgroundPixmap;
    backgroundPixmap.load(":/images/images/keyboard_layout3.png");
    QGraphicsPixmapItem *backgroundItem = new QGraphicsPixmapItem(backgroundPixmap);
    m_scene->setBackgroundBrush(QBrush(Qt::gray));
    m_scene->setSceneRect(250, 130, FixedWidth, FixedHeight);
    m_scene->addItem(backgroundItem);
    this->setScene(m_scene);
    this->fitInView(0, 0, FixedWidth, FixedHeight, Qt::KeepAspectRatio);
    //connect(m_timer, SIGNAL(timeout()), this, SLOT(update1()));
    m_timer = new QTimer(this);
    m_timer->start(16);

}

PadGraphicsView::~PadGraphicsView()
{


}

void PadGraphicsView::transPosToUV(float &x, float &y)
{
    cv::Mat trans_M = CaliCam::instance()->tr_mat;

    cv::Mat v = cv::Mat::zeros(3, 1, CV_MAKETYPE(trans_M.type(), 1));
    //std::cout << "m type " << trans_M.type() << " v type is " << v.type();
    v.at<double>(0) = x; v.at<double>(1) = y; v.at<double>(2) = 1;
    cv::Mat u = trans_M * v;
    x = u.at<double>(0); y = u.at<double>(1);
}

void PadGraphicsView::acceptOneTap(float x, float y)
{
    float r = 40;
    this->transPosToUV(x, y);
    float u = x * FixedWidth / 250 + 250, v = y * FixedHeight / 90 + 130;
    CircleItem* item = new CircleItem(u, v, r, m_scene, this);
    m_scene->addItem(item);
    connect(m_timer, SIGNAL(timeout()), item, SLOT(getSmaller()));
}

void PadGraphicsView::deleteItem(QGraphicsItem *item)
{
    delete item;
}
